package com.ymatou.shop.ui.activity.buyer;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.ymatou.shop.R;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.api.ApiResponse;
import com.ymatou.shop.cache.ImageCache;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.model.Order;
import com.ymatou.shop.ui.activity.BaseHeaderListActivity;
import com.ymatou.shop.ui.adapter.BaseAdapter;
import com.ymatou.shop.ui.view.PullToRefreshView;
import com.ymatou.shop.ui.view.item.BuyerOrderItemView;
import com.ymatou.shop.util.DateUtil;

public class OrderActivity extends BaseHeaderListActivity {

private static final int REQUEST_ID_LIST = 0x01;
	
	private BaseAdapter mAdapter;
	private List<Order> mOrderList;
	
	private String mLastId;
	private volatile boolean mReachEnd;
	private volatile boolean mLoadingList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);
		
		mOrderList = new ArrayList<Order>();
		mAdapter = new OrderListAdapter(this, mOrderList);
		
		setupViews();
		setupData(true);
	}
	
	@Override
	protected void setupViews() {
		super.setupViews();
		getTitleTextView().setText(R.string.title_order);
		getTitleLeftImageButton().setImageResource(R.drawable.back_icon);
		getTitleLeftImageButton().setVisibility(View.VISIBLE);
//		getTitleRightImageButton1().setImageResource(R.drawable.refresh_icon);
//		getTitleRightImageButton1().setVisibility(View.VISIBLE);
//		getTitleRightImageButton1().setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				getPullToRefreshView().updateWithoutOffset();
//				getPullToRefreshView().scrollToUpdate();
//				setupData(false);
//			}
//		});
		
		getListView().setAdapter(mAdapter);
		getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
//				Intent intent = new Intent(v.getContext(), OrderDetailActivity.class);
//				intent.putExtra(Constants.EXTRA_DATA, mProductList.get(position));
//				v.getContext().startActivity(intent);
			}
		});
		getPullToRefreshView().setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
			@Override
			public void onRefresh() {
				mLastId = null;
				setupData(false);
			}
		});
		
		changeLoadingViewState(false);
	}
	
	@Override
	protected void setupData(boolean useCache) {
		if (!mReachEnd) {
			if (!mLoadingList) {
				RequestInfo requestInfo = ApiRequest.getBuyerOrderList(mLastId);
				getCacheManager().register(REQUEST_ID_LIST, requestInfo, this);
			}
		}
	}
	
	@Override
	public BaseAdapter getAdapter() {
		return mAdapter;
	}
	
	@Override
	public void onCacheSuccess(int requestId, RequestInfo requestInfo,
			Object response) {
		if (requestId == REQUEST_ID_LIST) {
			List<Order> list = ApiResponse.getOrderList((String) response);
			if (list == null) {
				if (mOrderList.size() == 0) {
					changeErrorViewState(false);
				}
				return;
			}
			
			if (mOrderList.size() == 0) {
				mOrderList.addAll(list);
				
				mAdapter = new OrderListAdapter(this, mOrderList);
				getListView().setAdapter(mAdapter);
				getPullToRefreshView().setLastUpdated(new Date());
				
				changeLoadingViewState(true);
			} else {
				mOrderList.addAll(list);
				mAdapter.notifyDataSetChanged();
				getPullToRefreshView().onRefreshComplete(new Date());
			}
			
			if (list.isEmpty()) {
				mReachEnd = true;
			} else {
				mLastId = list.get(list.size() - 1).mId;
			}
			mLoadingList = false;
		} else {
			super.onCacheSuccess(requestId, requestInfo, response);
		}
	}
	
	@Override
	public void onCacheFailed(int requestId, RequestInfo requestInfo,
			CacheException error) {
		if (requestId == REQUEST_ID_LIST) {
			//////////test///
			if (mOrderList.size() == 0) {
				Order p = new Order();
				p.mId= "LP234234234";
				p.mNum = 50;
				p.mDownPayment = 80;
				p.mPrice = 100;
				p.mStatus = Order.STATUS_CREATE;
				p.mCreateTime = new Date();
				p.mLastPayTime = new Date(System.currentTimeMillis() + DateUtil.MILLIS_PER_DAY + DateUtil.MILLIS_PER_MINUTE + DateUtil.MILLIS_PER_SECOND * 5);
				p.mProductDescription = "开始！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！" +
						"测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！结束！";
				mOrderList.add(p);mOrderList.add(p);
				
				p = new Order();
				p.mId= "LP234234234";
				p.mNum = 50;
				p.mDownPayment = 80;
				p.mPrice = 100;
				p.mStatus = Order.STATUS_CREATE;
				p.mCreateTime = new Date();
				p.mProductDescription = "开始！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！" +
						"测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！测试描述，开始卖了！结束！";
				p.mStatus = Order.STATUS_RECEIVE;
				mOrderList.add(p);mOrderList.add(p);mOrderList.add(p);
				
				p.mStatus = Order.STATUS_PAYMENT;
				mOrderList.add(p);mOrderList.add(p);mOrderList.add(p);mOrderList.add(p);mOrderList.add(p);
				
				changeLoadingViewState(true);
			}
			
			if (mOrderList.size() > 0) {
				getPullToRefreshView().onRefreshComplete(new Date());
			} else {
				getPullToRefreshView().setLastUpdated(new Date());
			}
			return;
			/////////////
//			changeErrorViewState(false);
		} else {
			super.onCacheFailed(requestId, requestInfo, error);
		}
	}
	
	private static class OrderListAdapter extends BaseAdapter<Order> {
		
		public OrderListAdapter(Context context, List<Order> items) {
			super(context, items);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			BuyerOrderItemView itemView;
			if (convertView == null) {
				itemView = new BuyerOrderItemView(getContext(), mOnIconLoadCompleteListener);
			} else {
				itemView = (BuyerOrderItemView) convertView;
			}
			
			Order item = getItem(position);
			itemView.setData(item);
			
			return itemView;
		}
		
		private ImageCache.OnIconLoadCompleteListener mOnIconLoadCompleteListener = new ImageCache.OnIconLoadCompleteListener() {
			@Override
			public void onLoadComplete(String url, boolean success, Drawable drawable) {
				if (success) {
					notifyDataSetChanged();
				}
			}
		};
	}
}
